<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;
use think\Request;
use think\Response;
use think\response\Json;

class DictionaryData extends BaseController
{
    protected Model $model;
    public function initialize(): void
    {
        $this->model = new \app\model\DictionaryData();
    }

    /**
     * 获取字典
     * @param Request $request
     * @return Json
     */
    public function index(Request $request): Json
    {
        $dictionary_id = $request->param('dictionary_id');
        try {
            $data = $this->model->where('dictionary_id', $dictionary_id)->select();
            return $this->result(200,'',$data);
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return $this->result($e->getCode(),$e->getMessage());
        }
    }

    /**
     * 保存新建的资源
     *
     * @param Request $request
     * @return Response
     */
    public function save(Request $request): Response
    {
        try {
            $data = $request->post();
            $check = $this->model->where('name',$data['name'])
                ->where('dictionary_id', $data['dictionary_id'])->count();
            if ($check > 0) {
                return $this->result(403,'同字典下存在相同的数据源，换一个名称试试');
            }
            $result = $this->model->create($data);
            return $this->result(200,'添加成功',$result->toArray());
        }catch (\Exception $e){
            return $this->result($e->getCode(),$e->getMessage());
        }

    }

    /**
     * 保存更新的资源
     *
     * @param Request $request
     * @param int $id
     * @return Response
     */
    public function update(Request $request, int $id): Response
    {
        try {
            $data = $request->put();
            $condition = [
                ['name','=',$data['name']],
                ['dictionary_id','=',$data['dictionary_id']],
                ['id','<>',$id]
            ];
            $item = $this->model->where($condition)->count();
            if($item > 0){
                $this->result(403,'字典数据重复，请检查重试');
            }
            $result = $this->model->find($id);
            $result->save($data);
            return $this->result(200,'更新成功',$result->toArray());
        }catch (\Exception $e){
            return $this->result($e->getCode(),$e->getMessage());
        }
    }

    /**
     * 删除指定资源
     *
     * @param $id
     * @return Response
     */
    public function delete($id): Response
    {
        try {
           $this->model->where('id', $id)->delete();
            return $this->result(200,'删除成功');
        }catch (\Exception $e){
            return $this->result($e->getCode(),$e->getMessage());
        }

    }
}
